// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import gameData from "../gameData";
import mainManage from "../../framework/mainManage";
import AudioManage, {soundList} from "../../framework/AudioManage";

const {ccclass, property} = cc._decorator;

let curPeriodPet = ["小抖"];

@ccclass
export default class turnplateView extends cc.Component {

    @property(cc.Node)
    lightNode : cc.Node[] = [];

    @property(cc.Node)
    plateNode : cc.Node = null;

    @property(cc.Node)
    successView : cc.Node = null;

    @property(cc.Node)
    turnPlate : cc.Node = null;

    @property(cc.Sprite)
    successPic : cc.Sprite = null;

    @property(cc.SpriteFrame)
    picList : cc.SpriteFrame[] = [];

    @property(cc.Label)
    showTitle : cc.Label = null;

    @property(cc.Label)
    labList : cc.Label[] = [];

    @property(cc.Node)
    startPic : cc.Node[] = [];

    @property(cc.Node)
    lightningNode : cc.Node = null;

    @property(sp.Skeleton)
    spineNode : sp.Skeleton[] = [];

    @property(cc.Node)
    seeVideoView : cc.Node = null;

    @property(cc.Node)
    eggSkinView : cc.Node = null;

    @property(cc.Button)
    eggBtn : cc.Button = null;

    curPeriodPetIndex = 0;

    probabilityList = [];

    start () {
        if(gameData.eggSkinList[2] == 1){
            this.eggBtn.interactable = false;
        }
        cc.tween(this.node).to(0.2,{
            scale : 1
        }).start();

        for(let i in gameData.rewardList){
            this.probabilityList.push(gameData.rewardList[i]["chance"]);
        }
        this.lightShowAction();
        this.labList[0].string = "x" + gameData.lotteryTicket;
        this.labList[3].string = gameData.petPiece + "";
        this.labList[4].string = gameData.processPumpkinNumber + "";

        this.loadPetSkin(this.spineNode[2].node,curPeriodPet);
        this.loadPetSkin(this.spineNode[1].node,curPeriodPet);
        this.loadPetSkin(this.spineNode[3].node,curPeriodPet);

        if(gameData.shareVideoTimes == 5){
            this.labList[5].node.active = true;
            this.labList[6].node.active = false;
        }else{
            this.labList[5].node.active = false;
            this.labList[6].node.active = true;
            this.labList[1].string = "(" + gameData.shareVideoTimes + " / 5)";
        }

        this.countDown();
        if(gameData.freeLotteryTimes == 3){
            this.labList[2].string = "今日免费次数: 3/3";
        }else if(gameData.freeLotteryTimes == 2 || gameData.freeLotteryTimes == 1){
            this.schedule(this.countDown,1);
        }else {
            this.labList[2].string = "今日免费次数: 0/3";
        }

        // if(gameData.freeLotteryTimes > 0){
        //     if(gameData.lotteryTicket - 1 >= 0){
        //         this.startPic[0].active = true;
        //         this.startPic[1].active = false;
        //     }else{
        //         this.startPic[0].active = false;
        //         this.startPic[1].active = true;
        //     }
        // }else{
        //     this.startPic[0].active = true;
        //     this.startPic[1].active = false;
        // }
    }

    lightShowAction(){
        this.schedule(()=>{
            this.lightNode[0].active = !this.lightNode[0].active;
            this.lightNode[1].active = !this.lightNode[1].active;
        },0.3)
    }

    startRotate = false;
    randomGift = 0;
    lastAngle  = 0;
    timeWithTicket = false;

    judgeLotteryTicket(){
        if(this.startRotate) return;
        this.startRotate = true;

        if(!this.jumpWait){
            if(gameData.playLotteryLimit >= 120){
                mainManage.createToast("已达今日抽奖上线,明天再来吧");
                return;
            }
            gameData.playLotteryLimit++;
            if(gameData.freeLotteryTimes == 3){
                this.timeWithTicket = false;
                gameData.freeLotteryTimes -= 1;
                this.labList[2].string = "今日免费次数: 2/3";
            }else if(gameData.freeLotteryTimes == 2){
                let data = new Date().getTime();
                let min = ((data - gameData.lastLotteryTimes) % (1000 * 60 * 60)) / (1000 * 60);
                if(min >= 2){
                    this.timeWithTicket = false;
                    this.labList[2].string = "今日免费次数: 1/3";
                    gameData.freeLotteryTimes -= 1;
                }else{
                    if(gameData.lotteryTicket - 1 >= 0){
                        this.timeWithTicket = true;
                        gameData.lotteryTicket -= 1;
                        this.labList[0].string = "x" + gameData.lotteryTicket;
                    }else{
                        this.seeVideoView.active = true;
                        return
                    }
                }
            }else if(gameData.freeLotteryTimes == 1){
                let data = new Date().getTime();
                let min = ((data - gameData.lastLotteryTimes) % (1000 * 60 * 60)) / (1000 * 60);
                if(min >= 5){
                    this.timeWithTicket = false;
                    this.labList[2].string = "今日免费次数: 0/3";
                    gameData.freeLotteryTimes -= 1;
                    this.startPic[0].active = true;
                    this.startPic[1].active = false;
                }else{
                    if(gameData.lotteryTicket - 1 >= 0){
                        this.timeWithTicket = true;
                        gameData.lotteryTicket -= 1;
                        this.labList[0].string = "x" + gameData.lotteryTicket;
                    }else{
                        this.seeVideoView.active = true;
                        return
                    }
                }
            }else if(gameData.freeLotteryTimes == 0){
                if(gameData.lotteryTicket - 1 >= 0){
                    gameData.lotteryTicket -= 1;
                    this.labList[0].string = "x" + gameData.lotteryTicket;
                }else{
                    if(gameData.shareVideoTimes >= 5){
                        mainManage.createToast("今日已经没有抽奖次数啦，明天再来吧~");
                    }else{
                        mainManage.createToast("当前没有奖券哦，快去分享录屏获取奖券吧~");
                    }
                    return
                }
            }
            this.startAbstractGift();
        }else{
            this.jumpWait = false;
            gameData.freeLotteryTimes -= 1;
            this.startPic[0].active = true;
            this.startPic[1].active = false;
            this.timeWithTicket = false;
            this.labList[2].string = "今日免费次数: " + gameData.freeLotteryTimes + "/3";
            this.startAbstractGift();
        }
    }


    lastRotation = 0;
    lotteryTimes = 0;
    lastRandomIndex = -1;

    //开始抽奖
    startAbstractGift(){
        this.isStop = true;
        this.isCanOut = true;

        let showTicket = (Math.random() * 3) | 0;
        let index  = (this.lotteryTimes / 3) | 0;
        console.log(this.lotteryTimes,index * 3 + showTicket,this.lastRandomIndex,index);
        if(this.lotteryTimes == (index * 3 + showTicket) && this.lastRandomIndex != index){
            this.lastRandomIndex = index;
            this.randomGift = 0;
        }else{
            let random  = Math.random() * 100 | 0;
            console.log("random",random);
            if(random < this.probabilityList[0]){
                this.randomGift = 0;
            }else if(random >= this.probabilityList[0] && random <  this.probabilityList[0] + this.probabilityList[1]){
                this.randomGift = 1;
            }else if(random >= this.probabilityList[0] + this.probabilityList[1] && random <  this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2]){
                this.randomGift = 2;
            }else if(random >= this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2]  && random <  this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2] + this.probabilityList[3]){
                this.randomGift = 3;
            }else if(random >= this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2] + this.probabilityList[3]  && random <  this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2] + this.probabilityList[3] + this.probabilityList[4]){
                this.randomGift = 4;
            }else if(random >= this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2] + this.probabilityList[3] + this.probabilityList[4]  && random <  this.probabilityList[0] + this.probabilityList[1] + this.probabilityList[2] + this.probabilityList[3] + this.probabilityList[4] + this.probabilityList[5]){
                this.randomGift = 5;
            }
        }
        this.lotteryTimes++;
        console.log("liwu.....",this.randomGift);
        this.plateNode.angle = this.lastAngle;
        this.lightningNode.active = true;
        AudioManage.playSFX(soundList.spin,true,false,1);
        cc.tween(this.plateNode)
            .delay(0.1)
            .to(2.5,{angle : 360 * 12 + this.randomGift * 60 + 360},{easing : cc.easing.circInOut})
            .call(()=>{
                this.lastRotation = 0;
                this.lightningNode.active = false;
                this.lastAngle = this.randomGift * 60;
                this.successView.active = true;
                this.scheduleOnce(()=>{
                    this.successView.getChildByName("mask").getChildByName("single").active = true;
                },1);
                AudioManage.playSFX(soundList.spin,true,true,1);
                AudioManage.playSFX(soundList.rewardBG,false,false,2);
                if(gameData.rewardList[this.randomGift]["reward"] == "本期宠物"){
                    this.successPic.node.active  = false;
                    if(gameData.getPetProcessSkin()[this.curPeriodPetIndex] == 1){
                        this.showTitle.string = "已拥有该宠物，转换为30个宠物碎片~";
                    }else{
                        this.showTitle.string = curPeriodPet[0] + "x" + gameData.rewardList[this.randomGift]["num"];
                    }
                    this.spineNode[1].node.active =  true;
                    this.spineNode[1].setAnimation(0,"daiji",true);
                }else{
                    this.spineNode[1].node.active =  false;
                    this.successPic.node.active  = true;
                    this.showTitle.string = gameData.rewardList[this.randomGift]["reward"] + "x" + gameData.rewardList[this.randomGift]["num"];
                    this.successPic.spriteFrame = this.picList[this.randomGift];
                }
                this.getRewardSuccess = false;
            })
            .start();
    }

    loadPetSkin(node,name){
        for(let j in gameData.getPetShopData()){
            if(gameData.getPetShopData()[j]["psname"] == name){
                let data;
                this.curPeriodPetIndex = parseInt(j);
                if(parseInt(j) + 1 < 10){
                    data = "cw0" + (parseInt(j) + 1);
                }else{
                    data = "cw" + (parseInt(j) + 1);
                }
                cc.loader.loadRes("anim/" + data,sp.SkeletonData,(error, resource) =>{
                    let spk = node.getComponent(sp.Skeleton);
                    spk.skeletonData = resource;
                    node.active = true;
                    spk.setAnimation(0,"daiji",true);
                })
            }
        }
    }

    getRewardSuccess = false;
    getReward(event,data) {
        if(this.getRewardSuccess) return;
        this.getRewardSuccess = true;
        this.isCanOut = false;
        let callback = ()=>{
            this.startRotate = false;

            console.log(this.timeWithTicket);
            if(this.timeWithTicket){

            }else {
                gameData.lastLotteryTimes = new Date().getTime();
                this.timeWithTicket = false;
                if(gameData.freeLotteryTimes == 2 || gameData.freeLotteryTimes == 1){
                    gameData.lastLotteryTimes = new Date().getTime();
                    this.countDown();
                    this.schedule(this.countDown,1);
                }
            }

            if(gameData.freeLotteryTimes > 0){
                if(gameData.lotteryTicket - 1 >= 0){
                    this.startPic[0].active = true;
                    this.startPic[1].active = false;
                }else{
                    this.startPic[0].active = false;
                    this.startPic[1].active = true;
                }
            }else{
                this.startPic[0].active = true;
                this.startPic[1].active = false;
            }
            gameData.saveLotteryData();
        };

        if (parseInt(data) == 1) {
            //单倍领取
            this.giftEffect(gameData.rewardList[this.randomGift]["reward"],1,()=>{
                callback();
                this.getRewardSuccess = false;
                this.successView.active = false;
                this.isStop = false;
            });

        } else if (parseInt(data) == 2) {
            //双倍领取
            this.giftEffect(gameData.rewardList[this.randomGift]["reward"],2,()=>{
                callback();
                this.getRewardSuccess = false;
                this.successView.active = false;
                this.isStop = false;
            });
        }
    }

    giftEffect(name,type,callback){
        switch (name) {
            case "宠物碎片" :
                if(type == 1){
                    gameData.petPiece += gameData.rewardList[this.randomGift]["num"];
                    mainManage.createToast("获得宠物碎片x" + gameData.rewardList[this.randomGift]["num"]);
                }else{
                    gameData.petPiece +=  (2 * gameData.rewardList[this.randomGift]["num"]);
                    mainManage.createToast("获得宠物碎片x" + (2 * gameData.rewardList[this.randomGift]["num"]));
                }
                gameData.saveLotteryData();

                this.labList[3].string = gameData.petPiece + "";
                callback();
                break;
            case "本期宠物" :
                if(type == 1){
                    if(gameData.getPetProcessSkin()[this.curPeriodPetIndex] == 1){
                        gameData.petPiece += 30;
                        mainManage.createToast("获得宠物碎片x30");
                    }else{
                        mainManage.createToast("获得宠物" + curPeriodPet[0]);
                    }
                }else if(type == 2){
                    if(gameData.getPetProcessSkin()[this.curPeriodPetIndex] == 1){
                        gameData.petPiece += 60;
                        mainManage.createToast("获得宠物碎片x60");
                    }else{
                        gameData.petPiece += 30;
                        mainManage.createToast("获得" + curPeriodPet[0] + "x1,宠物碎片x30");
                    }
                }
                gameData.savePetSkin(this.curPeriodPetIndex);
                this.labList[3].string = gameData.petPiece + "";
                gameData.saveLotteryData();
                callback();
                break;
            case "神秘礼物" :
                if(type == 1){

                }else{

                }
                callback();
                break;
            case "苹果" :
                if(type == 1){
                    gameData.addSinglePumpkin(gameData.rewardList[this.randomGift]["num"]);
                    mainManage.createToast("获得苹果x" + gameData.rewardList[this.randomGift]["num"]);
                }else{
                    gameData.addSinglePumpkin(2 * gameData.rewardList[this.randomGift]["num"]);
                    mainManage.createToast("获得苹果x" + (2 * gameData.rewardList[this.randomGift]["num"]));
                }
                this.labList[4].string = gameData.processPumpkinNumber + "";
                callback();
                break;
            case "奥利给" :
                if(type == 1){
                    this.successPic.node.active  = false;
                    this.spineNode[0].node.active =  true;
                    mainManage.createToast("获得奥利给x" + gameData.rewardList[this.randomGift]["num"]);
                    this.spineNode[0].setAnimation(0,"texiao01",false);
                    this.spineNode[0].setCompleteListener(()=>{
                        this.spineNode[0].setCompleteListener(()=>{

                        });
                        this.spineNode[0].node.active = false;
                        callback();
                    });
                }else{
                    this.successPic.node.active  = false;
                    this.spineNode[5].node.active =  true;
                    this.spineNode[4].node.active =  true;
                    mainManage.createToast("获得奥利给x" +  (2 * gameData.rewardList[this.randomGift]["num"]));
                    this.spineNode[5].setAnimation(0,"texiao01",false);
                    this.spineNode[5].setCompleteListener(()=>{
                        this.spineNode[5].setAnimation(0,"texiao01",false);
                        this.spineNode[5].setCompleteListener(()=>{
                            this.spineNode[5].setCompleteListener(()=>{

                            });
                            this.spineNode[5].node.active = false;
                            callback();
                        })
                    });
                    this.spineNode[4].setAnimation(0,"texiao01",false);
                    this.spineNode[4].setCompleteListener(()=>{
                        this.spineNode[4].setAnimation(0,"texiao01",false);
                        this.spineNode[4].setCompleteListener(()=>{
                            this.spineNode[4].setCompleteListener(()=>{

                            });
                            this.spineNode[4].node.active = false;
                        })
                    });
                }
                break;
            case "奖券" :
                if(type == 1){
                    gameData.lotteryTicket += gameData.rewardList[this.randomGift]["num"];
                    mainManage.createToast("获得奖券x" + gameData.rewardList[this.randomGift]["num"]);
                }else{
                    gameData.lotteryTicket += (2 * gameData.rewardList[this.randomGift]["num"]);
                    mainManage.createToast("获得奖券x" +  (2 * gameData.rewardList[this.randomGift]["num"]));
                }
                this.labList[0].string = "x" + gameData.lotteryTicket;
                gameData.saveLotteryData();
                callback();
                break;
        }
    }


    callback = null;
    setCallback(callback){
        this.callback = callback;
    }


    countDown(){
        let times = new Date().getTime() - gameData.lastLotteryTimes;
        let leave5 = times % (24 * 3600 * 1000);
        let leave6 = leave5 % (3600 * 1000);
        let leave7 = leave6 % (60*1000);
        let min = Math.floor(leave6 / (60 * 1000));
        let sec = Math.round(leave7/1000);

        if(gameData.freeLotteryTimes == 3){
            this.startPic[0].active = false;
            this.startPic[1].active = true;
            return;
        }else if(gameData.freeLotteryTimes == 2 && min >= 2){
            this.startPic[0].active = false;
            this.startPic[1].active = true;
            this.labList[2].string = "今日免费次数: 2/3";
            this.unschedule(this.countDown);
            return;
        }else if(gameData.freeLotteryTimes == 1 && min >= 5){
            this.startPic[0].active = false;
            this.startPic[1].active = true;
            this.labList[2].string = "今日免费次数: 1/3";
            this.unschedule(this.countDown);
            return;
        }else if(gameData.freeLotteryTimes == 0){
            this.startPic[0].active = true;
            this.startPic[1].active = false;
            this.labList[2].string = "今日免费次数: 0/3";
            this.unschedule(this.countDown);
            return;
        }else{
            this.startPic[0].active = true;
            this.startPic[1].active = false;
        }
        if(sec == 0){
            this.labList[2].string = "免费倒计时 0" + min + ":00";
        }else{
            if(gameData.freeLotteryTimes == 2){
                if(60 - sec >= 10){
                    this.labList[2].string = "免费倒计时 0" + (1 - min) + ":" + (60 - sec);
                }else{
                    this.labList[2].string = "免费倒计时 0" + (1 - min) + ":0" + (60 - sec);
                }
            }else if(gameData.freeLotteryTimes == 1){
                if(60 - sec >= 10){
                    this.labList[2].string = "免费倒计时 0" + (4 - min) + ":" + (60 - sec);
                }else{
                    this.labList[2].string = "免费倒计时 0" + (4 - min) + ":0" + (60 - sec);
                }
            }
        }
    }

    isCanOut = false;
    backHome(){
        if(this.isCanOut){
            mainManage.createToast("抽奖完成才可以退出哦");
            return;
        }
        this.node.destroy();
        if(this.callback != null){
            this.callback();
        }
    }


    jumpWait  = false;
    btnClick(event,data){
        if(parseInt(data) == 1){
            this.seeVideoView.active = false;
            this.startRotate = false;
        }else if(parseInt(data) == 2){
            this.startPic[0].active = false;
            this.startPic[1].active = true;
            this.labList[2].string = "今日免费次数: " + gameData.freeLotteryTimes + "/3";
            this.unschedule(this.countDown);
            this.timeWithTicket = true;
            this.seeVideoView.active = false;
            this.jumpWait = true;
            this.startRotate = false;
        }
    }

    clickEgg = 0;
    showColorEgg(){
        if(this.clickEgg == 5){
            AudioManage.playSFX(soundList.colour);
            this.eggSkinView.active = true;
            let effect = this.eggSkinView.getChildByName("effect");
            let spk = effect.getComponent(sp.Skeleton);
            spk.setAnimation(0,"eggs1",false);
            spk.setCompleteListener(()=>{
                this.eggSkinView.getChildByName("mask").active =  true;
                this.scheduleOnce(()=>{
                    this.eggSkinView.getChildByName("mask").getChildByName("cancel").active =  true;
                },2)
            })
        }
        this.clickEgg++;
    }

    seeVideoGet(){
        this.eggBtn.interactable = false;
        gameData.eggSkinList[2] = 1;
        gameData.saveEggSkinList();
        gameData.lotteryTicket += 3;
        gameData.saveLotteryData();
        this.labList[0].string = "x" + gameData.lotteryTicket;
        mainManage.createToast("恭喜获得奖券x3");
        this.eggSkinView.active = false;
    }

    closeEggSkin(){
        this.clickEgg = 0;
        this.eggSkinView.active = false;
    }

    seeVideoGetTicket(){
        if(gameData.seeVideoGetTicket >= 20){
            mainManage.createToast("今日获取已达上限，明天再来吧");
            return;
        }
        gameData.seeVideoGetTicket++;
        gameData.lotteryTicket += 1;
        this.labList[0].string = "x" + gameData.lotteryTicket;
        gameData.saveLotteryData();
        mainManage.createToast("恭喜获得一张奖券");
    }

    isStop = false;
    protected update(dt: number): void {
        if(this.isStop) return;
        this.plateNode.angle += 0.5;
        this.lastRotation += 0.5;
    }
}
